package com.zhuoya.healthcard.net;





import com.blankj.utilcode.util.DeviceUtils;
import com.zhuoya.healthcard.BuildConfig;
import com.zhuoya.healthcard.contants.Contants;
import com.zhuoya.healthcard.update.UpdateUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public class HttpClient {



    /**
     * API服务器域名
     *
     * @return 域名
     */
    protected String getBaseUrl() {
        return Contants.uri;
    }



    protected <T> void requestWithSubscribe(Observable<ApiFrameResult<T>> observable, ApiRequestCallBack<T> mRequestCallBack) {
        observable.subscribeOn(Schedulers.io())
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe(new ApiRequestSubscriber<T>(mRequestCallBack));
    }


    protected <T> void requestWithSubscribeRetry(Observable<ApiFrameResult<T>> observable, ApiRequestCallBack<T> mRequestCallBack) {
        observable.retryWhen(new RetryWithDelay(Integer.MAX_VALUE, 5000)).subscribeOn(Schedulers.io())
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe(new ApiRequestSubscriber<>(mRequestCallBack));
    }



    /**
     * 获取网络请求工具,该方法用于返回参数非json格式，
     * 例如返回参数加密了需要解密成json
     */
    protected Retrofit getRetrofit() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS);

        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLogger());
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addNetworkInterceptor(logInterceptor);
        }
        OkHttpClient httpClient = builder.addInterceptor(chain -> {
            Request request = chain.request()
                    .newBuilder()
                    .addHeader("deviceId", UpdateUtil.getDeviceSerial())
                    .build();
            return chain.proceed(request);
        }).build();
        return new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(getBaseUrl())
                .client(httpClient)
                .build();
    }



}
